<?php

namespace App\Http\Controllers\Home;

use App\Models\Address;
use App\Models\BucketData;
use App\Models\Member;
use App\Models\Order;
use App\Models\Picture;
use App\Models\Shop;
use App\Models\ShopGoods;
use App\Models\WaterBill;
use App\Models\WechatSet;
use App\Models\Worker;
use App\Models\WxPay;
use App\Models\WxTpl;
use App\Models\XcxTpl;
use App\Support\Printer;
use App\Support\WechatLogin;
use EasyWeChat\Foundation\Application;

/**
 * 订单控制器
 */
class WorkerController extends BaseController
{

    public function __construct(
        Order $order,
        WxPay $wxPay,
        WechatSet $wechatSet,
        Picture $picture,
        ShopGoods $shopGoods,
        Shop $shop,
        Worker $worker,
        BucketData $bucketData,
        WaterBill $waterBill,
        Member $member,
        XcxTpl $xcxTpl,
        WxTpl $wxTpl,
        Address $address
    )
    {
        parent::__construct();
        $this->order = $order;
        $this->xcxPay = $wxPay;
        $this->wechatSet = $wechatSet;
        $this->picture = $picture;
        $this->shop = $shop;
        $this->shopGoods = $shopGoods;
        $this->worker = $worker;
        $this->bucketData = $bucketData;
        $this->waterBill = $waterBill;
        $this->member = $member;
        $this->xcxTpl = $xcxTpl;
        $this->wxTpl = $wxTpl;
        $this->address = $address;
    }

    public function getInfo()
    {
        $res = $this->worker->_getOneById(request('wid'));
        if (!$res) {
            return error('非法操作');
        }
        return success($res->toArray());
    }

    public function getIndex()
    {
        $shopInfo = $this->shop->_redisGetOneBySid($this->shop_id);
        if (in_array($shopInfo['send_mode'], [1, 3]) && request('type', 1) == 1) {
            return success(['order_list' => ['data' => []]]);
        }
        $res = $this->order->getWorkerOrderList();
        if (!$res) {
            return error($this->order->getError());
        }
        $ajaxData['order_list'] = $res;
        return success($ajaxData);
    }

    public function checkShopStatus()
    {
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        $msg = '';
        if ($shop['status'] != 1) {
            $msg = $shop['status'] == 2 ? '店铺已欠费，已暂停服务，请及时续费' : ($shop['status'] == -1 ? '店铺已关闭，如有问题请联系客服' : '系统维护升级，暂停服务');
        }
        return $msg;
    }

    public function getOrderList()
    {
        $res = $this->order->getWorkerSendOrderList();
        if (!$res) {
            return error($this->order->getError());
        }
        $ajaxData['order_list'] = $res;
        return success($ajaxData);
    }

    public function getOrderInfo()
    {
        $ajaxData['info'] = $this->order->getInfoById(request('id'));
        $type = request('type');
        if ($ajaxData['info'] && $type == 2) {
            $ajaxData['is_first'] = 1;
            $where['buyer_id'] = $ajaxData['info']['buyer_id'];
            $where['status'] = 20;
            $num = $this->order->_count($where, 'id');
//            $ajaxData['is_first'] = $num > 1 ? 0 : 1;
            $ajaxData['show_notice'] = $num > 1 ? 0 : 1;
//            if ($ajaxData['is_first']) {
//                $memberInfo = $this->member->_getOneById($ajaxData['info']['buyer_id'],'import_bucket');
//                if ($memberInfo['import_bucket']) {
//                    $ajaxData['is_first'] = 0;
//                }
//            }
        }
        return success($ajaxData);
    }

    public function getSend()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $result = $this->worker->checkMaxOrderNum(request('worker_id'));
        if (!$result) {
            return error($this->worker->getError() ? $this->worker->getError() : '未知错误');
        }
        $res = $this->order->workerSend();
        if (!$res) {
            return error($this->order->getError() ? $this->order->getError() : '未知错误');
        }
        return success($res);
    }

    public function getReSend()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $worker = $this->worker->_redisGetOneByWid($this->worker_id);
        if (!$worker['order_resend_auth']) {
            return error('暂无权限进行改派操作');
        }
        if (request('type')) {
            $result = $this->worker->checkMaxOrderNum(request('worker_id'));
            if (!$result) {
                return error('该送水工已达接单上限，无法改派');
            }
            $res = $this->order->workerReSend();
            if (!$res) {
                return error($this->order->getError() ? $this->order->getError() : '未知错误');
            }
            return success($res);
        }
        $rows = $this->worker->_getList(['shop_id' => request('sid'), 'status' => 1], 'id,name,code')->toArray();
        return success($rows);
    }

    public function getDetail()
    {
        $res = $this->order->getDetail();
        if (!$res) {
            return error('该订单不存在');
        }
        return success($res);
    }

    //线下订单
    public function postAdd()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $res = $this->order->addOrder();
        if (!$res) {
            return error($this->order->getError());
        }
        return success($res);
    }

    public function getDelete()
    {
        $res = $this->order->delete();
        if (!$res) {
            return error($this->order->getError());
        }
        return success($res);
    }

    public function postLogin()
    {
        $res = $this->worker->login();
        if (!$res) {
            return error($this->worker->getError());
        }
        return success($res);
    }

    public function getSearch()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $res = $this->worker->searchMember();
        if (!$res) {
            return error('未查询到相关用户信息');
        }
        return success($res);
    }

    public function postModifyPwd()
    {
        $res = $this->worker->modifyPwd();
        if (!$res) {
            return error($this->worker->getError());
        }
        return success($res);
    }

    public function getSelectData()
    {
        $member = [];
        if ($this->mid && request('from')) {
            $member = $this->address->_getOne(['mid' => $this->mid, 'is_default' => 1], 'mid as id,name,mobile,company_name,area_info,address');
            if ($member) {
                $member = $member->toArray();
            }
        }

        //type 0.水桶品牌 1.水票名称
        $where['admin_id'] = request('aid');
        $where['shop_id'] = request('sid');
        if (!request('type')) {
            $bucketData = $this->bucketData->_getJionList('category', $where, 'id,bucket_category_id,shop_id', [], 0, 'id,title')->toArray();
            if (!$bucketData) {
                return error('该店铺没有添加水桶品牌');
            }
            $arr = $bucketData[0];
            $arr['id'] = 0;
            $arr['bucket_category_id'] = 0;
            unset($arr['category']);
            $arr['title'] = '请选择水桶品牌';
            foreach ($bucketData as &$v) {
                $v['title'] = $v['category']['title'];
                unset($v['category']);
            }
            array_unshift($bucketData, $arr);
            if (request('from')) {
                return success(['bucket_list' => $bucketData, 'member' => $member]);
            } else {
                return success($bucketData);
            }
        }
        $where['status'] = ['>', 0];
        $waterBill = $this->waterBill->_getList($where, 'id,goods_name')->toArray();
        if (!$waterBill) {
            return error('该店铺没有添加水票');
        }
        if (request('from')) {
            return success(['bill_list' => $waterBill, 'member' => $member]);
        } else {
            return success($waterBill);
        }
    }

    public function postImport()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $wid = request('wid');
        $sid = request('sid');
        $aid = request('aid');
        if (!($wid && $sid && $aid)) {
            return error('非法操作');
        }
        $key = 'import_' . $wid . '_' . $sid . '_' . $aid;
        if ($this->redis->keys($key)) {
            return error('您已导入成功，请勿重复操作');
        }
        $worker = $this->worker->_redisGetOneByWid($wid);
        if (!$worker['import_auth']) {
            return error('暂无权限进行导入操作');
        }
        $res = $this->member->import($sid, $aid);
        if (!$res) {
            return error($this->member->getError() ? $this->member->getError() : '未知错误');
        }
        $this->redis->setex($key, 5, 1);
        return success('导入成功');
    }

    public function postComplete()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $wid = request('worker_id');
        $sid = request('sid');
        $aid = request('aid');
        if (!($wid && $sid && $aid)) {
            return error('非法操作');
        }
        $key = 'complete_' . $wid . '_' . $sid . '_' . $aid;
        if ($this->redis->keys($key)) {
            return error('您已操作成功，请勿重复操作');
        }
        $res = $this->order->complete();
        if (!$res) {
            return error($this->order->getError() ? $this->order->getError() : '未知错误');
        }
        $this->redis->setex($key, 10, 1);
        return success('操作成功');
    }

    public function postMove()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $res = $this->worker->move();
        if (!$res) {
            return error($this->worker->getError() ? $this->worker->getError() : '未知错误');
        }
        return success('操作成功');
    }

    public function getBindWx()
    {
        $res = $this->worker->_redisGetOneByWid($this->worker_id);
        if ($res['openid']) {
            return error('您已绑定微信');
        }
        $code = request('code');
        $wechatInfo = $this->wechatSet->_redisGetOneByAid(1);
        $appid = $wechatInfo['wx_app_id'];
        $app_secret = $wechatInfo['wx_app_secret'];
        $weixin = new WechatLogin($appid, $app_secret);
        $params = [
            'wid' => $this->worker_id,
            'sid' => $this->shop_id,
            'aid' => $this->admin_id
        ];
        if (!isset($code)) {
            $weixin->getCode(urlHome('worker', 'getBindWx', $params, 2));
        } else {
            $userInfo = $weixin->get_user_info($code);
            $url = url('/') . '/manager/bindwx.html?wid=' . $this->worker_id .
                '&sid=' . $this->shop_id . '&aid=' . $this->admin_id .
                '&openid=' . $userInfo['openid'];
            Header("Location: $url");
        }
    }

    public function getWxInfo()
    {
        $res = $this->worker->_redisGetOneByWid($this->worker_id);
        if ($res['openid']) {
            return error('您已绑定微信');
        }
        $code = request('code');
        $wechatInfo = $this->wechatSet->_redisGetOneByAid(1);
        $appid = $wechatInfo['wx_app_id'];
        $app_secret = $wechatInfo['wx_app_secret'];
        $weixin = new WechatLogin($appid, $app_secret);
        if (!isset($code)) {
            return error('非法操作');
        } else {
            $userInfo = $weixin->get_user_info($code);
            return success($userInfo);
        }
    }

    public function postBindWx()
    {
        $res = $this->worker->bindWx();
        if (!$res) {
            return error($this->worker->getError() ? $this->worker->getError() : '未知错误');
        }
        return success($res);
    }

    public function postRecoverBucket()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $worker = $this->worker->_redisGetOneByWid($this->worker_id);
        if (!$worker['recover_auth']) {
            return error('暂无权限进行取桶操作');
        }
        $res = $this->worker->recoverBucket();
        if (!$res) {
            return error($this->worker->getError() ? $this->worker->getError() : '未知错误');
        }
        return success($res);
    }

    /* 水票充值 */
    public function getBillCharge()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $waterBill = $this->waterBill->_getList(['shop_id' => $this->shop_id, 'status' => 1], 'id,goods_name')->toArray();
        if (!$waterBill) {
            return error('请先添加水票');
        }
        $member = $this->address->_getOne(['mid' => request('mid'), 'is_default' => 1], 'mid as id,name,mobile,company_name,area_info,address');
        if (!$member) {
            return error('该用户不存在');
        }
        $member = $member->toArray();
        $data['water_bill_list'] = $waterBill;
        $data['member_info'] = $member;
        return success($data);
    }

    public function postBillCharge()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $key = 'import_' . $this->worker_id . '_' . $this->shop_id . '_' . $this->admin_id;
        if ($this->redis->keys($key)) {
            return error('您已操作成功，请勿重复操作');
        }
        $worker = $this->worker->_redisGetOneByWid($this->worker_id);
        if (!$worker['charge_auth']) {
            return error('暂无权限进行充值操作');
        }
        $bill_id = intval(request('bill_id'));
        $bill_num = intval(request('bill_num'));
        $mid = intval(request('mid'));
        $money = intval(request('money'));
        $res = $this->member->charge($bill_id, $bill_num, $mid, $this->shop_id, $money, $worker);
        if (!$res) {
            return error($this->member->getError() ? $this->member->getError() : '未知错误');
        }
        return success('充值成功');
    }

    public function getRemoveBindWx()
    {
        $res = $this->worker->removeBindWx($this->worker_id);
        if (!$res) {
            return error($this->worker->getError() ? $this->worker->getError() : '未知错误');
        }
        return success($res);
    }

    public function getCreateOrder()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $ajaxData['goodsList'] = $this->shopGoods->_getList(['shop_id' => $this->shop_id, 'status' => 1], 'id,goods_name', ['sort' => 'asc'])->toArray();
        $where['id'] = $this->mid;
        $where['shop_id'] = $this->shop_id;
        $memberFields = 'id,name,mobile,address,company_name,area_info';
        $addressFields = 'id,mid,area_info,address';
        $condition['is_default'] = 1;
        $ajaxData['member_info'] = $this->member->_getJionOne('address', $where, $memberFields, $addressFields, $condition);
        $ajaxData['member_info']['default_address'] = $ajaxData['member_info']['address'];
        return success($ajaxData);
    }

    public function postCreateOrder()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $worker = $this->worker->_redisGetOneByWid($this->worker_id);
        if (!$worker['creat_order_auth']) {
            return error('暂无权限进行人工下单操作');
        }
        $adminId = request('aid');
        $goodsId = request('goods_id');
        $mid = request('mid');
        $goodsNum = request('goods_num');
        $money = request('money');
        $orderData = $this->order->creatOrder($mid, $this->shop_id, $adminId, $goodsId, $goodsNum, $money);
        if (!$orderData) {
            return error($this->order->getError() ? $this->order->getError() : '未知错误');
        }
        set_time_limit(0);
        ob_end_clean();
        header("Connection: close");
        header("HTTP/1.1 200 OK");
        header("Content-Type: application/json;charset=utf-8");// 如果前端要的是json则添加，默认是返回的html/text
        ob_start();
        echo json_encode(['status' => 1, 'data' => [], 'msg' => '下单成功']);// 输出结果到前端
        $size = ob_get_length();
        header("Content-Length: $size");
        ob_end_flush();
        flush();
        if (function_exists("fastcgi_finish_request")) { // yii或yaf默认不会立即输出，加上此句即可（前提是用的fpm）
            fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
        }
        ignore_user_abort(true);// 在关闭连接后，继续运行php脚本
        set_time_limit(0);
        $shopInfo = $this->shop->_redisGetOneBySid($this->shop_id);
        if (!$shopInfo['send_mode']) {
            $this->wxTpl->newOrderMsg($orderData, $this->shop_id);
        } else {
            // 打印订单
            (new Printer())->typeSetting($orderData);
        }
        exit;
    }

    public function postWxConfig()
    {
        $settings = $this->wechatSet->_getOne(['admin_id' => 1]);
        if (!$settings) {
            return false;
        }
        $config = [
            'app_id' => $settings['wx_app_id'],
            'secret' => $settings['wx_app_secret'],
            'aes_key' => $settings['wx_aes_key'],
        ];
        $app = new Application($config);
        $apis = [
            'checkJsApi',
            'openLocation',
            'getLocation'
        ];
        $js = $app->js;
        $js->setUrl(request('url'));
        $wxConfig = $js->config($apis, false, false, false);
        return success($wxConfig);
    }


}
